# include "LineHelper.h"

using namespace std;

namespace WuguiEngine
{
	namespace Graphics
	{
		DWORD LineHelper::LineVertexFVF = D3DFVF_XYZ|D3DFVF_DIFFUSE;
		LineHelper* LineHelper::instance = NULL;

		LineHelper::LineHelper(GraphicsDevice* device)
		{
			pDevice = device;
			isVertexDataChanged = false;
			LineCount = 0;
			pVertexBuffer = NULL;
		}

		void LineHelper::Initialize(GraphicsDevice* device)
		{
			instance = new LineHelper(device);
		}

		LineHelper* LineHelper::GetInstance()
		{
			if (instance == NULL)
			{
				throw "LineHelper not been initialized";
			}
			return instance;
		}

		void LineHelper::AddLine(D3DXVECTOR3 dot1, D3DXVECTOR3 dot2, 
			D3DCOLOR color)
		{
			LineVertex vertex;

			vertex.x = dot1.x;
			vertex.y = dot1.y;
			vertex.z = dot1.z;
			vertex.color = color;
			lineVertexData.push_back(vertex);

			vertex.x = dot2.x;
			vertex.y = dot2.y;
			vertex.z = dot2.z;
			vertex.color = color;
			lineVertexData.push_back(vertex);
			
			LineCount ++;
			isVertexDataChanged = true;
		}

		void LineHelper::Update(DWORD dt)
		{
			if (isVertexDataChanged)
			{
				if (pVertexBuffer != NULL)
				{
					pVertexBuffer->Release();
				}
				pDevice->CreateVertexBuffer(
					LineCount * 2 * sizeof(LineVertex),
					LineVertexFVF,
					D3DPOOL_DEFAULT, &pVertexBuffer);
				void* pData;
				pVertexBuffer->Lock(0, 0, (void**)&pData, 0);
				memcpy(pData, &lineVertexData[0], sizeof(LineVertex) * lineVertexData.size());
				pVertexBuffer->Unlock();
				isVertexDataChanged = false;
			}
		}

		void LineHelper::Render(DWORD dt)
		{
			pDevice->SetRenderState(D3DRS_ZENABLE, false);
			pDevice->SetStreamSource(pVertexBuffer, sizeof(LineVertex));
			pDevice->SetFVF(LineVertexFVF);
			pDevice->DrawPrimitive(D3DPT_LINELIST, 0, LineCount);
			pDevice->SetRenderState(D3DRS_ZENABLE, true);
		}

		void LineHelper::Dispose()
		{
			pVertexBuffer->Release();
			lineVertexData.clear();
		}
	}
}